package com.stella.ieproductivitybackend.interceptor;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.stella.ieproductivitybackend.utils.JWTUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * JWT 验证拦截器
 */
public class JWTInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 判断当前拦截到的是 Controller 的方法，还是其它资源
        if (!(handler instanceof HandlerMethod)) {
            // 若当前拦截到的不是动态方法，则直接放行
            return true;
        }

        Map<String,Object> map = new HashMap<>();
        // 令牌建议是放在请求头中，获取请求头中令牌
        String token = request.getHeader("Authorization");
        try{
            JWTUtils.verify(token);  // 验证令牌
            return true;  // 放行请求
        } catch (SignatureVerificationException e) {
            map.put("msg", "无效签名");
        } catch (TokenExpiredException e) {
            map.put("msg", "token 过期");
        } catch (AlgorithmMismatchException e) {
            map.put("msg", "token 算法不一致");
        } catch (Exception e) {
            map.put("msg", "token 失效");
        }
        map.put("state", false);  // 设置状态
        map.put("reset", true);  // 重新登录
        // 将 map 转化成 json，response 使用的是 jackson
        String json = new ObjectMapper().writeValueAsString(map);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().print(json);
        return false;
    }
}